//
//  LogonViewController.m
//  RongRTCMeeting
//  
//  Created by LiuLinhong on 2017/08/09.
//  Copyright © 2017年 Beijing Rongcloud Network Technology Co. , Ltd. All rights reserved.
//

#import "LogonViewController.h"
#import "MeetingWindowController.h"
#import "MeetingViewController.h"
#import "AppDelegate.h"
#import "CommonUtility.h"
#import "LogonOptionTableViewCellView.h"

#define kEverLaunched @"everLaunched"
#define kDefaultRoomNumber @"defaultRoomNumber"
#define kUserInputName @"UserInputName"
#define kRoomNumberMin 100000
#define kRoomNumberMax 999999

#define kTCP @"tcp"
#define kQUIC @"quic"
#define kNAME @"name"
#define kCMP @"cmp"
#define kCMPTLS @"cmptls"
#define kSNIFFER @"sniffer"
#define kSNIFFERTLS @"sniffertls"
#define kTOKEN @"token"
#define kDER @"der"
#define kTempCache [NSTemporaryDirectory() stringByAppendingPathComponent:@"Cache"]

static NSString *staticKeyToken;
static NSUserDefaults *tempUserDefaults = nil;
static RongRTCConnectionState connectionState = -1;

@interface LogonViewController() <NSTableViewDataSource,NSTableViewDelegate>
{
    NSUserDefaults *settingUserDefaults;
    BOOL isRoomNumberInput;
    NSString *lastInputName;
}

@property (nonatomic, strong) NSArray *configListArray, *styleConfigListArray;
@property (nonatomic, strong) NSURL *tokenURL;
@property (nonatomic, strong) NSString *keyToken;
@property (nonatomic, strong) NSPanel *envPanel;
@property (nonatomic, strong) NSTableView *tableView;
@property (nonatomic, strong) NSString *customAppKey, *customTokenURL, *customCmpURL;
@property (nonatomic, assign) BOOL isCustomVersion;

@end

@implementation LogonViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear
{
    [super viewWillAppear];
    [self initLogonView];
    
    [self queryKeyTokenInRelease];
    
    if (self.rongRTCEngine.delegate && self.rongRTCEngine.delegate != self.logonRongRTCEngineDelegateImpl)
        self.rongRTCEngine.delegate = self.logonRongRTCEngineDelegateImpl;
}

- (void)initLogonView
{
    [self initUserDefaults];
    isRoomNumberInput = NO;
    lastInputName = @"";
    self.isCustomVersion = NO;
    self.isConnectionQuic = NO;
    self.isLogonContentViewExpanded = NO;
    self.logonRongRTCEngineDelegateImpl = [[LogonRongRTCEngineDelegateImpl alloc] initWithViewController:self];
    self.logonOptionTableViewDelegateSource = [[LogonOptionTableViewDelegateSource alloc] initWithViewController:self];
    self.logonViewBuilder = [[LogonViewBuilder alloc] initWithViewController:self];
    self.settingPanelBuilder = [[SettingPanelBuilder alloc] initWithViewController:self];
    
    if (self.observerIndex == RongRTC_User_Observer)
    {
        self.isLogonContentViewExpanded = YES;
        [self expandButtonPressed];
        [self.logonViewBuilder.expandButton setEnabled:NO];
    }
    else
        [self.logonViewBuilder.expandButton setEnabled:YES];
    
    NSString *enterRoomNumber, *inputUserName;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL everLaunched = [userDefaults boolForKey:kEverLaunched];
    if (everLaunched)
    {
        enterRoomNumber = [userDefaults valueForKey:kDefaultRoomNumber];
        inputUserName = [userDefaults valueForKey:kUserInputName];
    }
    else
    {
        [userDefaults setBool:YES forKey:kEverLaunched];
        NSInteger randomRoomNumber = [CommonUtility getRandomNumber:kRoomNumberMin to:kRoomNumberMax];
        enterRoomNumber = [NSString stringWithFormat:@"%zd", randomRoomNumber];
        inputUserName = @"";
        [userDefaults setObject:enterRoomNumber forKey:kDefaultRoomNumber];
        [userDefaults setObject:@"" forKey:kUserInputName];
        [userDefaults synchronize];
    }
    
    self.logonViewBuilder.channelIDTextField.stringValue = enterRoomNumber;
    self.logonViewBuilder.userNameTextField.stringValue = inputUserName;
    isRoomNumberInput = YES;
    [self updateJoinRoomButtonSocket:NO textFieldInput:isRoomNumberInput];
}

- (void)queryKeyTokenInRelease
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    self.customAppKey = [userDefaults valueForKey:kCustomAPPKey];
    self.customTokenURL = [userDefaults valueForKey:kCustomTokenURL];
    self.customCmpURL = [userDefaults valueForKey:kCustomCMPURL];
    
    if (self.customAppKey && self.customTokenURL && self.customCmpURL &&
        ![[self.customAppKey stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]
        && ![[self.customTokenURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]
        && ![[self.customCmpURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""])
    {
        self.isCustomVersion = YES;
        self.tokenURL = [NSURL URLWithString:self.customTokenURL];
        [self getKeyTokenFromServer:@""];
    }
    else
    {
        self.isCustomVersion = NO;
        [self requestPRODConfigList];
    }
}

#pragma mark - init UserDefaults
- (void)initUserDefaults
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *docDir = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
    NSString *settingUserDefaultPath = [docDir stringByAppendingPathComponent:File_SettingUserDefaults_Plist];
    DLog(@"LLH...... Log settingUserDefaultPath: %@", settingUserDefaultPath);
    BOOL isPlistExist = [CommonUtility isFileExistsAtPath:settingUserDefaultPath];
    settingUserDefaults = [LogonViewController shareSettingUserDefaults];
    
    if (!isPlistExist)
    {
        [settingUserDefaults setObject:@(Value_Default_ResolutionRatio) forKey:Key_ResolutionRatio];
        [settingUserDefaults setObject:@(Value_Default_AudioOnly) forKey:Key_AudioOnly];
        [settingUserDefaults setObject:@(Value_Default_Observer) forKey:Key_Observer];
        [settingUserDefaults setObject:@(Value_Default_CloseCamera) forKey:Key_CloseCamera];
        [settingUserDefaults setObject:@(Value_Default_FrameRate) forKey:Key_FrameRate];
        [settingUserDefaults setObject:@(Value_Default_CodeRate) forKey:Key_CodeRate];
        [settingUserDefaults setObject:@(Value_Default_MinCodeRate) forKey:Key_CodeRateMin];
        [settingUserDefaults setObject:@(Value_Default_Connection_Style) forKey:Key_ConnectionStyle];
        [settingUserDefaults setObject:@(Value_Default_Coding_Style) forKey:Key_CodingStyle];
        [settingUserDefaults setObject:@(Value_Default_GPUFilter) forKey:Key_GPUFilter];
        [settingUserDefaults setObject:@(Value_Default_SRTPEncrypt) forKey:Key_SRTPEncrypt];
        [settingUserDefaults synchronize];
    }
    
    self.resolutionRatioIndex = [[settingUserDefaults valueForKey:Key_ResolutionRatio] integerValue];
    self.isAudioOnly = [[settingUserDefaults valueForKey:Key_AudioOnly] boolValue];
    self.observerIndex = [[settingUserDefaults valueForKey:Key_Observer] integerValue];
    self.closeCameraIndex = [[settingUserDefaults valueForKey:Key_CloseCamera] integerValue];
    self.frameRateIndex = [[settingUserDefaults valueForKey:Key_FrameRate] integerValue];
    self.codeRateMaxIndex = [[settingUserDefaults valueForKey:Key_CodeRate] integerValue];
    self.codeRateMinIndex = [[settingUserDefaults valueForKey:Key_CodeRateMin] integerValue];
    self.connectionStyleIndex = [[settingUserDefaults valueForKey:Key_ConnectionStyle] integerValue];
    self.codingStyleIndex = [[settingUserDefaults valueForKey:Key_CodingStyle] integerValue];
    self.isGPUFilter = [[settingUserDefaults valueForKey:Key_GPUFilter] boolValue];
    self.isSRTPEncrypt = [[settingUserDefaults valueForKey:Key_SRTPEncrypt] boolValue];
}

- (void)requestPRODConfigList
{
    __weak typeof(self) weakSelf = self;
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:kURLConfigListPROD]];
    request.HTTPMethod = @"Get";
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        DLog(@"LLH...... PROD ConfigList response");
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (!data)
            {
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                weakSelf.styleConfigListArray = [userDefaults valueForKey:@"SealRTCServerPRODConfigList"];
                DLog(@"LLH...... PROD ConfigList response data is nil, use cache data! PROD configList: %@", weakSelf.configListArray);
                if (weakSelf.styleConfigListArray && [weakSelf.styleConfigListArray count] > 0)
                {
                    NSDictionary *configDic = (NSDictionary *)weakSelf.styleConfigListArray[0];
                    NSArray *configDicKeys = [configDic allKeys];
                    NSDictionary *tmpConfigDic;
                    if (self.isConnectionQuic)
                    {
                        if ([configDicKeys containsObject:kQUIC])
                            tmpConfigDic = (NSDictionary *)configDic[kQUIC];
                    }
                    else
                    {
                        if ([configDicKeys containsObject:kTCP])
                            tmpConfigDic = (NSDictionary *)configDic[kTCP];
                    }
                    self.tokenURL = [NSURL URLWithString:tmpConfigDic[kTOKEN]];
                    [weakSelf getKeyTokenFromServer:@""];
                }
                else
                    [self requestPRODConfigList];
                return;
            }
            
            NSError *err;
            weakSelf.styleConfigListArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
            DLog(@"LLH...... queried PROD configList: %@", weakSelf.configListArray);
            if (weakSelf.styleConfigListArray && [weakSelf.styleConfigListArray count] > 0)
            {
                NSDictionary *configDic = (NSDictionary *)weakSelf.styleConfigListArray[0];
                NSArray *configDicKeys = [configDic allKeys];
                NSDictionary *tmpConfigDic;
                if (self.isConnectionQuic)
                {
                    if ([configDicKeys containsObject:kQUIC])
                        tmpConfigDic = (NSDictionary *)configDic[kQUIC];
                }
                else
                {
                    if ([configDicKeys containsObject:kTCP])
                        tmpConfigDic = (NSDictionary *)configDic[kTCP];
                }
                self.tokenURL = [NSURL URLWithString:tmpConfigDic[kTOKEN]];
                [weakSelf getKeyTokenFromServer:@""];
            }
            else
                [self requestPRODConfigList];
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:weakSelf.configListArray forKey:@"SealRTCServerPRODConfigList"];
            [userDefaults synchronize];
        });
    }];
    
    [task resume];
    DLog(@"LLH...... request ConfigList");
}

- (void)getKeyTokenFromServer:(NSString *)selectedServer
{
    __weak typeof(self) weakSelf = self;
    NSString *postBody = [NSString stringWithFormat:@"uid=%@&appid=%@", [CommonUtility hardwareUUID], kAPPKey];
    if (self.isCustomVersion)
        postBody = [NSString stringWithFormat:@"uid=%@&appid=%@", [CommonUtility hardwareUUID], self.customAppKey];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.tokenURL];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [postBody dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        DLog(@"LLH...... token response");
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (!data)
            {
                DLog(@"LLH...... Token Response data is nil, ERROR!");
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 5), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [self getKeyTokenFromServer:selectedServer];
                });
                
                return;
            }
            
            weakSelf.keyToken = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            staticKeyToken = weakSelf.keyToken;
            DLog(@"LLH...... keyToken: %@", weakSelf.keyToken);
            
            if (self.isCustomVersion)
            {
                weakSelf.rongRTCEngine = [[RongRTCEngine alloc] initEngine:self.customCmpURL];
                weakSelf.rongRTCEngine.engineTLSCertificateData = nil;
            }
            else
            {
                NSDictionary *styleConfigDic = (NSDictionary *)weakSelf.styleConfigListArray[0];
                NSArray *configDicKeys = [styleConfigDic allKeys];
                NSDictionary *configDic;
                if (self.isConnectionQuic)
                {
                    if ([configDicKeys containsObject:kQUIC])
                        configDic = (NSDictionary *)styleConfigDic[kQUIC];
                }
                else
                {
                    if ([configDicKeys containsObject:kTCP])
                        configDic = (NSDictionary *)styleConfigDic[kTCP];
                }
                
                NSString *cmp = configDic[kCMP];
                NSString *certURL = configDic[kDER];
                
                if (certURL)
                {
                    NSString *fileName = [NSString stringWithFormat:@"PROD%@", [certURL lastPathComponent]];
                    NSString *certFilePath = [kTempCache stringByAppendingPathComponent:fileName];
                    
                    BOOL fileExist = [CommonUtility isDownloadFileExists:fileName atPath:kTempCache];
                    if (!fileExist)
                    {
                        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:certURL]];
                        [data writeToFile:certFilePath atomically:NO];
                    }
                    
                    NSData *certData = [NSData dataWithContentsOfFile:certFilePath];
                    weakSelf.rongRTCEngine = [[RongRTCEngine alloc] initEngine:cmp];
                    weakSelf.rongRTCEngine.engineTLSCertificateData = certData;
                }
                else
                {
                    weakSelf.rongRTCEngine = [[RongRTCEngine alloc] initEngine:cmp];
                    weakSelf.rongRTCEngine.engineTLSCertificateData = nil;
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self updateJoinRoomButtonSocket:YES textFieldInput:isRoomNumberInput];
                weakSelf.logonViewBuilder.versionTextField.stringValue = [NSString stringWithFormat:@"%@    %@", APP_Version, selectedServer];
            });
            [weakSelf.rongRTCEngine setDelegate:self.logonRongRTCEngineDelegateImpl];
        });
    }];
    
    [task resume];
    DLog(@"LLH...... token send request");
}

#pragma mark - NSTableViewDataSource
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return [self.configListArray count];
}

#pragma mark - NSTableViewDelegate
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSTextField *cellTextField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 100, 30)];
    cellTextField.bordered = NO;
    cellTextField.editable = NO;
    cellTextField.alignment = NSTextAlignmentCenter;
    cellTextField.backgroundColor = [NSColor clearColor];
    NSDictionary *configDic = (NSDictionary *)self.configListArray[row];
    if ([configDic[@"name"] isEqualToString:@""] || !configDic[@"name"]) {
        cellTextField.stringValue = @"Server";
    }else
        cellTextField.stringValue = configDic[@"name"];
    
    return cellTextField;
}

// 设置行高
- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 20;
}

- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row
{
    return YES;
}

- (void)updateJoinRoomButtonSocket:(RongRTCConnectionState)state
{
    connectionState = state;
    switch (state)
    {
        case RongRTC_ConnectionState_Connected:
            [self updateJoinRoomButtonSocket:YES textFieldInput:isRoomNumberInput];
            break;
        case RongRTC_ConnectionState_Disconnected:
            [self updateJoinRoomButtonSocket:NO textFieldInput:isRoomNumberInput];
            break;
        default:
            break;
    }
}

- (void)roomNumberTextFieldDidChange:(NSTextField *)textField
{
    if (![self.logonViewBuilder.channelIDTextField.stringValue isEqualToString:@""]
        && ![self.logonViewBuilder.channelIDTextField.stringValue isEqualToString:@""])
        isRoomNumberInput = YES;
    else
        isRoomNumberInput = NO;
    
    BOOL success;
    switch (connectionState) {
        case RongRTC_ConnectionState_Connected:
            success = YES;
            break;
        case RongRTC_ConnectionState_Disconnected:
            success = NO;
            break;
        default:
            success = YES;
            break;
    }
    
    [self updateJoinRoomButtonSocket:success textFieldInput:isRoomNumberInput];
}

- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
{
    if (commandSelector == @selector(insertNewline:))
    {
        //        NSEventModifierFlags modifierFlags = [NSApplication sharedApplication].currentEvent.modifierFlags;
        //        if let modifierFlags = NSApplication.shared().currentEvent?.modifierFlags, (modifierFlags.rawValue & NSEventModifierFlags.shift.rawValue) != 0
        //        if ( modifierFlags && NSEventModifierFlagCommand ) {
        //        } else {
        //        }
        // https://developer.apple.com/library/prerelease/content/qa/qa1454/_index.html
        // If we want to insert new line instead of default action, which will complete editing.
        //        textView.insertNewlineIgnoringFieldEditor(self)
        //        [textView insertNewlineIgnoringFieldEditor:self];
        [self joinRoomButtonPressed];
        return YES;
    }
    return NO;
}

#pragma mark - NSTextFieldDelegate
//- (void)controlTextDidEndEditing:(NSNotification *)obj
//{
//    int PasswordMinLimit = 12;  //定义限制字符的最小长度
//    if (obj.object == self.logonViewBuilder.userNameTextField)
//    {
//        //currentPasswordTextField你要限制字符的输入框  还有的话继续添加
//        if ([[self.currentPasswordTextField stringValue] length] < 12)
//        {
//            self.reminderCurrentPassword.stringValue = @"The number of characters less than the minimum limit!";  //提示框提示内容
//            self.reminderCurrentPassword.hidden = NO;  //提示框  看需要加不加
//            return;
//        }
//        else
//        {
//            self.reminderCurrentPassword.hidden = YES;
//        }
//    }
//}

- (void)controlTextDidChange:(NSNotification *)obj
{
    if (![self validateUserName:self.logonViewBuilder.userNameTextField.stringValue withRegex:@"[a-zA-Z|\\s|\u4e00-\u9fa5]*"])
    {
        self.logonViewBuilder.userNameTextField.stringValue = lastInputName;
        return;
    }
    
    NSInteger maxLimit = 12;
    NSInteger tmpLen = [self convertStringToCharInt:self.logonViewBuilder.userNameTextField.stringValue];
    if (tmpLen > maxLimit)
        self.logonViewBuilder.userNameTextField.stringValue = lastInputName;
    else
        lastInputName = self.logonViewBuilder.userNameTextField.stringValue;
}


- (BOOL)validateUserName:(NSString *)userName withRegex:(NSString *)regex
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:userName];
}

#pragma mark - change join button enable/unenable
- (void)updateJoinRoomButtonSocket:(BOOL)success textFieldInput:(BOOL)input
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (success && input)
        {
            self.logonViewBuilder.joinRoomButton.enabled = YES;
//            self.logonViewBuilder.joinRoomButton.backgroundColor = JoinButtonEnableBackgroundColor;
//            [self.logonViewBuilder.joinRoomButton setTitle:NSLocalizedString(@"logon_input_enter_meeting_room", nil) forState:UIControlStateNormal];
//            [self.logonViewBuilder.joinRoomButton setTitle:NSLocalizedString(@"logon_input_enter_meeting_room", nil) forState:UIControlStateHighlighted];
        }
        else
        {
            self.logonViewBuilder.joinRoomButton.enabled = NO;
//            self.logonViewBuilder.joinRoomButton.backgroundColor = JoinButtonUnableBackgroundColor;
            
            if (input)
            {
//                [self.logonViewBuilder.joinRoomButton setTitle:NSLocalizedString(@"logon_input_logon_meeting_room", nil) forState:UIControlStateNormal];
//                [self.logonViewBuilder.joinRoomButton setTitle:NSLocalizedString(@"logon_input_logon_meeting_room", nil) forState:UIControlStateHighlighted];
            }
            else
            {
//                [self.logonViewBuilder.joinRoomButton setTitle:NSLocalizedString(@"logon_input_need_room_number", nil) forState:UIControlStateNormal];
//                [self.logonViewBuilder.joinRoomButton setTitle:NSLocalizedString(@"logon_input_need_room_number", nil) forState:UIControlStateHighlighted];
            }
        }
    });
}

#pragma mark - 加入房间点击事件
- (void)joinRoomButtonPressed
{
    NSString *inputUserName = [self.logonViewBuilder.userNameTextField.stringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if ([inputUserName isEqualToString:@""])
    {
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"logon_input_meeting_nick_name", nil)];
        [attrStr addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, 5)];
        [attrStr addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:14.0] range:NSMakeRange(0, 5)];
        
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc]init];
        paragraph.alignment = NSTextAlignmentCenter;
        [attrStr addAttribute:NSParagraphStyleAttributeName
                                 value:paragraph
                                 range:NSMakeRange(0, 5)];
        
        self.logonViewBuilder.userNameTextField.placeholderAttributedString = attrStr;
        return;
    }
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.logonViewBuilder.channelIDTextField.stringValue forKey:kDefaultRoomNumber];
    [userDefaults setObject:self.logonViewBuilder.userNameTextField.stringValue forKey:kUserInputName];
    [userDefaults synchronize];
    
    [self.settingPanelBuilder closeSettingPanel];
    NSStoryboard *storyboard = [NSStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    
    MeetingWindowController *meetingWindowController = [storyboard instantiateControllerWithIdentifier:@"MeetingWindowController"];
//    [meetingWindowController.window setAnimationBehavior:NSWindowAnimationBehaviorDocumentWindow];
    [meetingWindowController.window makeFirstResponder:nil];
    
    MeetingViewController *meetingViewController = (MeetingViewController *)meetingWindowController.contentViewController;
    meetingViewController.channelID = self.logonViewBuilder.channelIDTextField.stringValue;
    
    // 2.强引用这个Window，不然这个Window会在跳转之后的瞬间被销毁
    AppDelegate *appDelegate = (AppDelegate *)[NSApplication sharedApplication].delegate;
    appDelegate.mainWindowController = meetingWindowController;
    [meetingWindowController.window makeKeyAndOrderFront:nil];
    
    // 4.关闭现在的登录窗口
    [self.view.window orderOut:nil];
}

#pragma mark - 展开选项点击事件
- (void)expandButtonPressed
{
    DLog(@"LLH...... expandButtonPressed: %zd", self.isLogonContentViewExpanded);
    NSMutableAttributedString *attributedString;
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont systemFontOfSize:14], NSFontAttributeName,
                           kLogonTextColor, NSForegroundColorAttributeName, nil];
    
    if (self.isLogonContentViewExpanded)
    {
        [self.logonViewBuilder.logonOptionView removeFromSuperview];
        attributedString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"logon_meeting_option_down", nil) attributes:attrs];
    }
    else //▲▼
    {
        [self.logonMainView addSubview:self.logonViewBuilder.logonOptionView];
        attributedString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"logon_meeting_option_up", nil) attributes:attrs];
    }
    
    [attributedString setAlignment:NSTextAlignmentCenter range:NSMakeRange(0, [attributedString length])];
    [self.logonViewBuilder.expandButton setAttributedTitle:attributedString];
    
    self.isLogonContentViewExpanded = !self.isLogonContentViewExpanded;
}

#pragma mark - 身份选项点击事件
- (void)identitySwitchAction:(id)sender
{
    DJSwitchControl *switchControl = (DJSwitchControl *)sender;
    DLog(@"LLH...... identitySwitchAction: %zd", switchControl.isOn);
    
    RongRTCUserType userType = switchControl.isOn ? RongRTC_User_Observer : RongRTC_User_Normal;
    [settingUserDefaults setObject:@(userType) forKey:Key_Observer];
    [settingUserDefaults synchronize];
    
    if (userType == RongRTC_User_Observer)
    {
        self.isLogonContentViewExpanded = YES;
        [self expandButtonPressed];
        [self.logonViewBuilder.expandButton setEnabled:NO];
        
        LogonOptionTableViewCellView *cell = (LogonOptionTableViewCellView *)self.logonOptionTableViewDelegateSource.cellDic[@(0)];
        [cell.cellSwitch setOn:NO];
    }
    else
        [self.logonViewBuilder.expandButton setEnabled:YES];
}

#pragma mark - 会议选项Switch事件
- (void)logonOptionSwitchAction:(id)sender
{
    DJSwitchControl *switchControl = (DJSwitchControl *)sender;
    DLog(@"LLH...... logonOptionSwitchAction Row: %zd   isOn: %zd", switchControl.row, switchControl.isOn);
    switch (switchControl.row)
    {
        case 0:
        {
            RongRTCAudioVideoType avType = switchControl.isOn ? RongRTC_User_Only_Audio : RongRTC_User_Audio_Video;
            [settingUserDefaults setObject:@(avType) forKey:Key_CloseCamera];
        }
            break;
        case 1:
        {
//            [settingUserDefaults setObject:@(switchControl.isOn) forKey:Key_AudioOnly];
        }
            break;
        default:
            break;
    }
    [settingUserDefaults synchronize];
}

#pragma mark - 分辨率Radio点击事件
- (void)resolutionRadioButtonAction:(id)sender
{
    NSMatrix *matrix = (NSMatrix *)sender;
    DLog(@"LLH...... resolutionRadioButtonAction: %zd", matrix.selectedColumn);
    
    if (matrix.selectedRow == 1 && matrix.selectedColumn == 0)
        self.resolutionRatioIndex = 2;
    else
        self.resolutionRatioIndex = matrix.selectedColumn;
    
    [settingUserDefaults setObject:@(self.resolutionRatioIndex) forKey:Key_ResolutionRatio];
    [settingUserDefaults synchronize];
    [self.settingPanelBuilder reloadChoiceData:self.resolutionRatioIndex];
}

- (void)setRepresentedObject:(id)representedObject
{
    [super setRepresentedObject:representedObject];
}

- (NSInteger)convertStringToCharInt:(NSString *)strtemp
{
    NSInteger strlength = 0;
    char *p = (char *)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (NSInteger i = 0; i < [strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++)
    {
        if (*p)
        {
            p++;
            strlength++;
        }
        else
            p++;
    }
    //    return (strlength+1)/2;
    return strlength;
}

+ (NSString *)getKeyToken
{
    return staticKeyToken;
}

+ (void)setConnectionState:(RongRTCConnectionState)state
{
    connectionState = state;
}

#pragma mark - share setting UserDefaults
+ (NSUserDefaults *)shareSettingUserDefaults
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tempUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"settingUserDefaults"];
    });
    return tempUserDefaults;
}

@end

